/**
 * @file    drv_wdg.c
 * @brief   MCU驱动-看门狗驱动
 * @author  Liuwei
 * @version 1.0.1
 * @date    2023-04-18
 * 
 * @copyright Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version   <th>Author   <th>Description
 * <tr><td>2023-04-18 <td>1.0.1     <td>Liuwei   <td>首次创建
 * </table>
 */
/* includes ------------------------------------------------------------------*/
#include "drv_wdg.h"
#include "drv_gpio.h"
#include "cfg_prj.h"
/* macro/define --------------------------------------------------------------*/  
#define WDG_ENABLE
/* typedef -------------------------------------------------------------------*/

/* local functions -----------------------------------------------------------*/

/* static variables ----------------------------------------------------------*/

/* global variables ----------------------------------------------------------*/

/** ------------------------------------------------------------------------- *
  *                             Global function
 ** ------------------------------------------------------------------------- */
/**
 * @brief  初始化看门狗
 * @param  cycle : 监控周期
 */
void drv_wdg_init(uint32_t cycle)
{
#ifdef WDG_ENABLE
	SYS_UnlockReg();
	
    drv_gpio_cfg_mode(HARD_WDG_PORT , HARD_WDG_PIN ,GPIO_MODE_OUTPUT);
    
	if (SYS_IS_WDT_RST()) {
        /* Set up DPD power down mode */
        CLK->PMUSTS |= CLK_PMUSTS_CLRWK_Msk;
        CLK_SetPowerDownMode(CLK_PMUCTL_PDMSEL_DPD);

        CLK_SET_WKTMR_INTERVAL(CLK_PMUCTL_WKTMRIS_128);
        CLK_ENABLE_WKTMR();

        CLK_PowerDown();
    }
	
	SYS_LockReg();
	
	CLK_EnableModuleClock(WDT_MODULE);
    CLK_SetModuleClock(WDT_MODULE, CLK_CLKSEL1_WDTSEL_LIRC, 0);
	
	NVIC_EnableIRQ(WDT_IRQn);
	
	SYS_UnlockReg();
	
	if(WDT_TIMEOUT_1638MS == cycle)
		WDT_Open(WDT_TIMEOUT_2POW14, WDT_RESET_DELAY_1026CLK, TRUE, TRUE);
	else
		WDT_Open(WDT_TIMEOUT_2POW16, WDT_RESET_DELAY_1026CLK, TRUE, TRUE);
	
    WDT_EnableInt();
	
	SYS_LockReg();
#endif
}

/**
 * @brief  看门狗喂狗
 * @param  void
 */
void drv_wdg_feed(void)
{
#ifdef WDG_ENABLE
	SYS_UnlockReg();
	
	WDT_RESET_COUNTER();
	
	SYS_LockReg();
	
	drv_gpio_toggle_pin(HARD_WDG_PORT , HARD_WDG_PIN);
#endif
}


/** ------------------------------------------------------------------------- *
  *                              Local function
 ** ------------------------------------------------------------------------- */
 
/********** Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD *********/
